import React, { useEffect, useState, useRef } from 'react';
import i18next from 'i18next';
import { useTranslation } from 'react-i18next';
import { connect, useDispatch, useSelector } from 'react-redux';

import { trashIcon } from '../assets/icons';
import { Input as StyledInput } from '../components';
import { StateType } from '../__data__/store';
import { api } from '../__data__/services/main';
import {
  HWrapper,
  Header,
  Papper,
  Wrapper,
  List,
  ListItem,
  DeleteButton,
  Input,
  Form,
} from './todo-style';
import { addSlice } from '../__data__/slices/add';

type TodoElement = {
  id: number;
  title: string;
};

type PageState = {
  todos: Array<TodoElement>;
  taskInputValue: string;
  inputError: string | boolean;
};

const PageFunc = () => {
  const [inputError, setinputError] = useState<null | string>('');
  const inputValue = useSelector((state: StateType) => state.add.value);
  const dispatch = useDispatch();
  const inputRef = useRef<HTMLInputElement>();
  const [addTodo, addTodoRequestData] = api.useAddTodoMutation();

  const handleInputChange = (event) => {
    dispatch(addSlice.actions.change(event.target.value));
    setinputError(null);
  };

  useEffect(() => {
    if (addTodoRequestData.isError) {
      setinputError('Ошибка')
    }
  }, [addTodoRequestData.isLoading])

  const handleAddSubmit = (event) => {
    event.preventDefault();

    if (inputValue === '') {
      setinputError('Нельзя создать задачу с пустым значением');
      return;
    }

    addTodo({ value: inputValue });
    dispatch(addSlice.actions.change(''));
  };

  useEffect(() => {
    inputRef?.current?.focus();
  }, []);

  const deleteElement = () => {};

  return (
    <Wrapper>
      <HWrapper red={false}>
        <Header>
          {i18next.t('todo.header.logo.text', { userName: 'Фёдор' }) as string}
        </Header>
      </HWrapper>

      <Form as="form" onSubmit={handleAddSubmit}>
        <StyledInput
          ref={inputRef}
          error={inputError}
          value={inputValue}
          onChange={handleInputChange}
        />
        <button type="submit">Добавть</button>
      </Form>

      <Papper>
        <ToDos onDelete={deleteElement} />
      </Papper>
    </Wrapper>
  );
};

const Element = ({ children, number, onDelete }) => (
  <ListItem>
    {number}. {children}{' '}
    <DeleteButton onClick={onDelete} title="Кнопка удалть элемент">
      <img aria-hidden src={trashIcon} />
    </DeleteButton>
  </ListItem>
);

const ToDos = ({ onDelete }) => {
  const { t, i18n } = useTranslation();
  const { isLoading, data } = api.useTodoListQuery();
  const value = useSelector((state: StateType) => state.add.value);
  const dispatch = useDispatch();

  const handleDo = () => {
    dispatch(addSlice.actions.change('value'));
  };

  if (isLoading) {
    return <h1 onClick={handleDo}>{t('todo.todo.loading') as string}</h1>;
  }

  return (
    <>
      <h1>{t('todo.header.logo.text') as string}</h1>
      <button
        onClick={() => {
          i18n.changeLanguage(i18n.language === 'ru' ? 'en' : 'ru');
        }}>
        {t('todo.todo.lng.button.text') as string}
      </button>
      <List>
        {data?.body?.map((el, index) => (
          <Element
            key={el.id}
            onDelete={() => onDelete(el.id)}
            number={index + 1}>
            {el.title}
          </Element>
        ))}
      </List>
    </>
  );
};

export default PageFunc;
